"use client"

import { useState, useEffect } from 'react'
import { textStyles } from '../../../lib/fontConfig'
import { useProgressManager } from '../../../lib/progressManager'

interface FindCharGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

export function FindCharGame({ targetChar, onGameEnd }: FindCharGameProps) {
  const [gameGrid, setGameGrid] = useState<string[]>([])
  const [selectedIndex, setSelectedIndex] = useState<number | null>(null)
  const [correctIndex, setCorrectIndex] = useState<number>(-1)
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(30)
  const [gameOver, setGameOver] = useState(false)
  const [level, setLevel] = useState(1)
  const [correctAnswers, setCorrectAnswers] = useState(0)
  const [totalQuestions, setTotalQuestions] = useState(0)

  const { generateSmartContent } = useProgressManager()

  // 生成游戏网格
  const generateGrid = () => {
    const gridSize = 6 // 3x2网格
    const grid = new Array(gridSize).fill(targetChar)
    
    // 获取相似汉字
    const similarChars = getSimilarCharacters(targetChar)
    const differentChar = similarChars[Math.floor(Math.random() * similarChars.length)]
    
    // 随机选择一个位置放置不同的字
    const differentIndex = Math.floor(Math.random() * gridSize)
    grid[differentIndex] = differentChar
    
    setGameGrid(grid)
    setCorrectIndex(differentIndex)
    setSelectedIndex(null)
  }

  // 获取相似汉字
  const getSimilarCharacters = (char: string): string[] => {
    const similarCharsMap: { [key: string]: string[] } = {
      '木': ['本', '术', '朱', '未', '末'],
      '人': ['入', '八', '大', '个', '从'],
      '水': ['永', '冰', '求', '泳', '氷'],
      '火': ['灭', '炎', '烧', '焰', '炸'],
      '土': ['士', '王', '干', '工', '上'],
      '山': ['出', '岀', '凸', '屮', '丨'],
      '口': ['日', '曰', '回', '囗', '吕'],
      '心': ['必', '忄', '恋', '思', '想']
    }
    
    return similarCharsMap[char] || ['本', '术', '朱']
  }

  // 处理点击
  const handleCellClick = (index: number) => {
    if (gameOver || selectedIndex !== null) return
    
    setSelectedIndex(index)
    setTotalQuestions(prev => prev + 1)
    
    setTimeout(() => {
      if (index === correctIndex) {
        setScore(prev => prev + 100 * level)
        setCorrectAnswers(prev => prev + 1)
        playSuccessEffect()
        
        // 生成下一题
        setTimeout(() => {
          generateGrid()
          if (level < 5) {
            setLevel(prev => prev + 1)
          }
        }, 1000)
      } else {
        playErrorEffect()
        // 显示正确答案
        setTimeout(() => {
          generateGrid()
        }, 1500)
      }
    }, 500)
  }

  // 成功效果
  const playSuccessEffect = () => {
    // 这里可以添加成功音效和动画
    console.log('正确！')
  }

  // 错误效果
  const playErrorEffect = () => {
    // 这里可以添加错误音效和动画
    console.log('错误！')
  }

  // 游戏计时器
  useEffect(() => {
    if (timeLeft > 0 && !gameOver) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      setGameOver(true)
      onGameEnd(score, correctAnswers, totalQuestions)
    }
  }, [timeLeft, gameOver, score, correctAnswers, totalQuestions, onGameEnd])

  // 初始化游戏
  useEffect(() => {
    generateGrid()
  }, [targetChar])

  if (gameOver) {
    return (
      <div className="h-full flex items-center justify-center">
        <div className="bg-white/90 backdrop-blur-sm rounded-2xl p-8 shadow-lg text-center max-w-md">
          <div className="text-6xl mb-4">🎉</div>
          <h3 className={`${textStyles.sectionTitle} text-gray-800 mb-4`}>
            游戏结束！
          </h3>
          <div className="space-y-2 mb-6">
            <div className={`${textStyles.tag} text-blue-700`}>
              最终得分: {score}
            </div>
            <div className={`${textStyles.tag} text-green-700`}>
              正确率: {totalQuestions > 0 ? Math.round((correctAnswers / totalQuestions) * 100) : 0}%
            </div>
            <div className={`${textStyles.tag} text-purple-700`}>
              答对题目: {correctAnswers}/{totalQuestions}
            </div>
          </div>
          <button
            onClick={() => window.location.reload()}
            className={`
              ${textStyles.primaryButton} px-6 py-3 
              bg-gradient-to-r from-blue-500 to-purple-500 text-white rounded-xl
              hover:from-blue-600 hover:to-purple-600 transition-all duration-300
            `}
          >
            再玩一次
          </button>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col">
      {/* 游戏标题和状态 */}
      <div className="text-center mb-6">
        <h3 className={`${textStyles.sectionTitle} text-gray-800 mb-2`}>
          找出与"{targetChar}"不同的字
        </h3>
        <div className="flex justify-center space-x-6 text-sm">
          <div className="flex items-center space-x-1">
            <span className="text-blue-600">⏰</span>
            <span className={`${textStyles.tag} text-blue-700 font-bold`}>
              {timeLeft}秒
            </span>
          </div>
          <div className="flex items-center space-x-1">
            <span className="text-green-600">🎯</span>
            <span className={`${textStyles.tag} text-green-700 font-bold`}>
              {score}分
            </span>
          </div>
          <div className="flex items-center space-x-1">
            <span className="text-purple-600">📊</span>
            <span className={`${textStyles.tag} text-purple-700 font-bold`}>
              第{level}关
            </span>
          </div>
        </div>
      </div>

      {/* 游戏网格 */}
      <div className="flex-1 flex items-center justify-center">
        <div className="grid grid-cols-3 gap-4 max-w-md">
          {gameGrid.map((char, index) => (
            <button
              key={index}
              onClick={() => handleCellClick(index)}
              disabled={selectedIndex !== null}
              className={`
                w-20 h-20 rounded-xl text-3xl font-bold transition-all duration-300
                ${selectedIndex === index
                  ? index === correctIndex
                    ? 'bg-green-500 text-white shadow-lg scale-110'
                    : 'bg-red-500 text-white shadow-lg scale-110'
                  : selectedIndex !== null && index === correctIndex
                    ? 'bg-green-400 text-white shadow-lg'
                    : 'bg-white border-2 border-gray-300 text-gray-800 hover:border-blue-400 hover:shadow-md hover:scale-105'
                }
                ${selectedIndex !== null ? 'cursor-not-allowed' : 'cursor-pointer'}
              `}
            >
              {char}
            </button>
          ))}
        </div>
      </div>

      {/* 提示信息 */}
      <div className="text-center mt-4">
        <p className={`${textStyles.description} text-gray-600`}>
          {selectedIndex === null 
            ? '仔细观察，找出不同的汉字！' 
            : selectedIndex === correctIndex
              ? '🎉 太棒了！找对了！'
              : '❌ 再仔细看看哦！'
          }
        </p>
      </div>
    </div>
  )
} 